import Vue from 'vue'
import Vuex from 'vuex'

import indModel from './modules/indModel'
import indReview from './modules/indReview'
import indPush from './modules/indPush'
import indLib from './modules/indLib'
import evaluation from './modules/evaluation'
import role from './modules/role'

import { parseJsonStr, stringifyObj, findChildItem, getPermissions, getMenus } from '@utility/utility'

// import { getUserpermissions } from '@api/modules/user.js'
import { getUserLoginRecordCount } from '@api/api.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    activeRouter: '',
    currMsg: null,
    noticeMessage: 0,
    cachedPages: [],
    permissions: null,
    userPermissions: null,
    isTestEnv: process.env.VUE_APP_BUILD_ENV === 'test',
    vipDays: 30,
    loginCount: null, // 用户登录系统次数
    leftMenuPcode: null,
    boardTabs: 'week',
  },
  getters: {
    currMsg: state => state.currMsg,
    noticeMessage: state => state.noticeMessage,
    cachedPages: state => state.cachedPages,
    permissions: state => {
      const permissions = state.permissions ?? parseJsonStr(localStorage.getItem('PERMISSION_CODES'))
      if (permissions && permissions.length) {
        return permissions
      }
      return null
    },
    leftNavMenus: state => {
      console.log('state :>> ', state)
      const userPermissions = state.userPermissions ?? parseJsonStr(localStorage.getItem('PSKH_PERMISSIONS'))
      if (userPermissions) {
        console.log('%c⧭', 'color: #f200e2', state.leftMenuPcode)
        if (state.leftMenuPcode) {
          const menu =
            findChildItem(userPermissions, state.leftMenuPcode, { fieldId: 'belongPage', fieldChild: 'menuVOS' }) || {}
          const { node } = menu
          if (node) {
            return node.menuVOS
          }
        }
      }
      return userPermissions
    },
    isTestEnv: state => state.isTestEnv,
    loginCount: state => {
      if (state.loginCount === null) {
        const loginCount = localStorage.getItem('ZB_LOGIN_COUNT')
        if (loginCount) {
          return Number(loginCount)
        }
      }
      return state.loginCount
    },
    vipDays: state => {
      if (state.role.userInfo) {
        return state.role.userInfo.vipDays || 0
      } else {
        const userInfo = localStorage.getItem('PSKH_USERINFO')
        if (userInfo) {
          state.role.userInfo = parseJsonStr(userInfo)
          return state.role.userInfo.vipDays || 0
        }
      }
      return 30
    },
    headMenuCode: state => {
      if (state.headMenuCode) {
        return state.headMenuCode
      } else {
        const headMenuCode = localStorage.getItem('HEAD_MENU_CODE')
        if (headMenuCode) {
          return headMenuCode
        }
      }
      return ''
    },
    leftMenuPcode: state => state.leftMenuPcode,
  },
  actions: {
    async getLoginCount(context) {
      if (!localStorage.pskh_userId) {
        return false
      }
      const { status, data = 0 } = await getUserLoginRecordCount(localStorage.pskh_userId)
      if (status === 200) {
        context.commit('setLoginCount', data)
      }
    },
    async getUserPermissions(context) {
      if (context.getters['role/userInfo']) {
        if (context.getters['role/isOperateRole']) {
          let userPermissions = null
          userPermissions = [
            {
              belongPage: 'JXKH_SYSTEM',
              menuCode: '',
              menuName: '运营管理',
              menuImagePath: 'iconfont kh-yunyingguanli',
              menuVOS: [
                {
                  belongPage: 'JXKH_DELAY_MANAGE',
                  menuCode: '',
                  menuName: '延期管理',
                  menuImagePath: '',
                },
              ],
            },
          ]
          context.commit('setUserPermissions', userPermissions)
          context.commit('setPermissions', { list: userPermissions, homePage: false })
        } else {
          const userPermissions = getMenus(context.getters)
          context.commit('setUserPermissions', userPermissions)
          context.commit('setPermissions', { list: userPermissions, homePage: true })
        }
      }
    },
  },
  mutations: {
    setActiveRouter(state, router) {
      state.activeRouter = router
    },
    setCurrMsg(state, val) {
      state.currMsg = val
    },
    setNoticeMessage(state, val) {
      state.noticeMessage = val
    },
    setCachedPages(state, val) {
      state.cachedPages = val
    },
    clearCommonAll(state) {
      state.activeRouter = null
      state.currMsg = null
      state.noticeMessage = null
      state.cachedPages = []
      state.userRoles = null
      state.orgName = null
      state.orgId = null
      state.userInfo = null
      state.loginCount = null
      state.permissions = null
      state.headMenuCode = ''
    },
    // TODO 合并 多余的 permission
    setUserPermissions(state, val) {
      state.userPermissions = val
      localStorage.setItem('PSKH_PERMISSIONS', stringifyObj(val))
    },
    setLoginCount(state, n) {
      state.loginCount = n
      localStorage.setItem('ZB_LOGIN_COUNT', n)
    },
    setLeftMenuPcode(state, pcode) {
      state.leftMenuPcode = pcode
    },
    setPermissions(state, { list = [], homePage = false }) {
      let permissions = []
      if (list.length) {
        permissions = getPermissions(list, permissions)
      }
      if (homePage) {
        permissions.push('homePage')
      }
      localStorage.setItem('PERMISSION_CODES', stringifyObj(permissions))
      state.permissions = permissions
    },
  },
  modules: { indModel, indReview, indPush, indLib, evaluation, role },
})
